﻿using AxDSOFramer;
using EnvDTE;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VisualPoint.Controls.Actions;
using VisualPoint.Controls.Views;

namespace VisualPoint.Controls
{
    /// <summary>
    /// Interaction logic for MyControl.xaml
    /// </summary>
    public partial class VisualPointControl : UserControl
    {
        #region Fields

        ToolWindowPane _ToolWindowPane;

        private bool _created;
        private AxFramerControl _framerControl;
        System.Windows.Forms.Integration.WindowsFormsHost _host;
        private Microsoft.Office.Interop.PowerPoint.Application _Application;
        private Presentation _presentation;
        private SlideShowView SlideShowView
        {
            get
            {
                try
                {
                    return _Application.ActivePresentation.SlideShowWindow.View;
                }
                catch
                {
                    return null;
                }
            }
        }

        //private object SlideShowView
        //{
        //    get
        //    {
        //        return _Application.ActivePresentation.Windows..SlideShowWindow.View;
        //    }
        //}

        #endregion

        #region Events

        public event EventHandler Fullscreen;
        protected void DoFullscreen()
        {
            if (Fullscreen != null)
            {
                Fullscreen.Invoke(this, EventArgs.Empty);
            }
        }

        public event EventHandler Minimize;
        protected void DoMinimize()
        {
            if (Minimize != null)
            {
                Minimize.Invoke(this, EventArgs.Empty);
            }
        }

        public event EventHandler NormalSize;
        protected void DoNormalSize()
        {
            if (NormalSize != null)
            {
                NormalSize.Invoke(this, EventArgs.Empty);
            }
        }

        #endregion

        #region Methods

        public VisualPointControl()
        {
            InitializeComponent();
        }
        public VisualPointControl(ToolWindowPane toolWindowPane)
            : this()
        {
            _ToolWindowPane = toolWindowPane;
        }

        private void CreatePowerPointApplication()
        {
            if (_created)
            {
                return;
            }
            _created = true;
            try
            {
                // create the Windows Forms host
                _host = new System.Windows.Forms.Integration.WindowsFormsHost();

                AxHost.Children.Add(_host);

                // Create the ActiveX control that hosts the PowerPoint application
                _framerControl = new AxFramerControl();
                _host.Child = _framerControl;

                _framerControl.CreateNew("PowerPoint.Show.8");
                _framerControl.Titlebar = false;
                _framerControl.BorderStyle = DSOFramer.dsoBorderStyle.dsoBorderNone;

                _presentation = _framerControl.ActiveDocument as Presentation;

                if (_presentation != null)
                {
                    _Application = _presentation.Application;

                    _Application.SlideShowNextSlide += _Application_SlideShowNextSlide;
                    _Application.SlideShowOnNext += _Application_SlideShowOnNext;
                    _Application.SlideShowOnPrevious += _Application_SlideShowOnPrevious;
                    _Application.SlideSelectionChanged += _Application_SlideSelectionChanged;
                    _Application.SlideShowNextClick += _Application_SlideShowNextClick;

                    _Application.PresentationBeforeSave += _Application_PresentationBeforeSave;

                    _Application.SlideShowBegin += _Application_SlideShowBegin;
                    _Application.SlideShowEnd += _Application_SlideShowEnd;
                }

                VisualPoint.Controls.Environments.Environment.Current.CreateWindowConfiguration("VisualPoint");
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }


        void _Application_SlideShowBegin(SlideShowWindow Wn)
        {
            Dispatcher.Invoke(new Action(delegate()
            {
                try
                {
                    //toolbar.Visibility = System.Windows.Visibility.Collapsed;

                    //rowDef1.Height = GridLength.Auto;
                    //rowDef3.Height = new GridLength(1, GridUnitType.Pixel);

                    ActionList.Visibility = Visibility.Collapsed;

                    _framerControl.Invalidate();
                }
                catch { }
            }));
        }

        void _Application_SlideShowEnd(Presentation Pres)
        {
            try
            {
                Dispatcher.Invoke(new Action(delegate()
                {
                    try
                    {
                        ////rowDef1.Height = new GridLength(75, GridUnitType.Star);
                        ////rowDef3.Height = new GridLength(25, GridUnitType.Star);

                        ActionList.Visibility = Visibility.Visible;
                    }
                    catch { }
                }));
            }
            catch { }
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            Dispatcher.Invoke(new Action(delegate()
            {
                try
                {
                    toolbar.Visibility = System.Windows.Visibility.Collapsed;

                    //rowDef1.Height = GridLength.Auto;
                    //rowDef3.Height = new GridLength(1, GridUnitType.Pixel);

                    ActionList.Visibility = Visibility.Collapsed;

                    _framerControl.Invalidate();
                }
                catch { }
            }));
        }


        private void SetMessage(string message)
        {
            //Message.Dispatcher.BeginInvoke((Action)(() => Message.Text += message + "\n"));
        }

        void _Application_PresentationBeforeSave(Presentation Pres, ref bool Cancel)
        {
            ActionList.BeforeSave();
        }

        void _Application_SlideSelectionChanged(SlideRange SldRange)
        {
            if (SldRange.Count > 0)
            {
                SlideShowView slideShow = SlideShowView;
                if (slideShow == null)
                {
                    try
                    {
                        Dispatcher.Invoke(new Action(delegate() { ActionList.SlideSelectionChange(SldRange[1]); }));
                    }
                    catch (Exception ex)
                    {
                        HandleException(ex);
                    }
                }
            }

            //SetMessage("Slide Selection On Changed");
        }

        void _Application_SlideShowOnPrevious(SlideShowWindow Wn)
        {
            SetMessage("Slide Show On Previous");
        }

        void _Application_SlideShowOnNext(SlideShowWindow Wn)
        {
            SetMessage("Slide Show On Next");
        }

        void _Application_SlideShowNextSlide(SlideShowWindow Wn)
        {
            //VisualPoint.Controls.Environments.Environment.Current.WriteOutputWindow("Slide Show Next Slide");
            try
            {
                ActionList.RunActions(Wn.View.LastSlideViewed, ActionTime.Exit);
            }
            catch
            { }
            ActionList.RunActions(Wn.View.Slide, ActionTime.Start);
            
        }

        void _Application_SlideShowNextClick(SlideShowWindow Wn, Effect nEffect)
        {
            //VisualPoint.Controls.Environments.Environment.Current.WriteOutputWindow("Slide Show Next Click");
            if (nEffect != null)
            {
                //VisualPoint.Controls.Environments.Environment.Current.WriteOutputWindow("Slide Show Next Click: " + nEffect.Index);
                int index = nEffect.Index;
                SlideShowView slideShow = SlideShowView;
                if (slideShow != null)
                {
                    index = SlideShowView.GetClickIndex();
                }
                string name = nEffect.DisplayName;
                if (index > 0)
                {
                    ActionList.RunActions(Wn.View.Slide, (ActionTime)index);
                }
            }
        }

        private void btnPrevious_Click(object sender, RoutedEventArgs e)
        {
            Catch(() => SlideShowView.Previous());
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            Catch(() => SlideShowView.Next());
        }

        private void btnRestart_Click(object sender, RoutedEventArgs e)
        {
            Catch(() => SlideShowView.GotoSlide(1, Microsoft.Office.Core.MsoTriState.msoTrue));
        }

        private void btnFullscreen_Click(object sender, RoutedEventArgs e)
        {
            VisualPoint.Controls.Environments.Environment.Current.ResizeFullScreen();
            _framerControl.Invalidate();
        }

        private void btnMinimize_Click(object sender, RoutedEventArgs e)
        {
            DoMinimize();
        }

        private void btnNormalSize_Click(object sender, RoutedEventArgs e)
        {
            VisualPoint.Controls.Environments.Environment.Current.ResizeNormal();
            _framerControl.Invalidate();
        }

        private void VisualPointWindow_Loaded(object sender, RoutedEventArgs e)
        {
            CreatePowerPointApplication();
        }

        #region Utilities

        private void VisualPointWindow_Unloaded(object sender, RoutedEventArgs e)
        {
            //if (!_framerControl.IsDisposed)
            //{
            //    _framerControl.Dispose();
            //}
        }



        delegate void SafeAction();

        private void Catch(SafeAction d)
        {
            try
            {
                d.Invoke();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        private void HandleException(Exception ex)
        {
            //Message.Text = ex.Message;
        }

        #endregion

        #endregion

        #region Presentation File

        private void btnNewPresentation_Click(object sender, RoutedEventArgs e)
        {
            Presentation p = _Application.Presentations.Add(MsoTriState.msoFalse);
            
            
        }

        private void btnOpenPresentation_Click(object sender, RoutedEventArgs e)
        {
            FileDialog dlg = _Application.get_FileDialog(MsoFileDialogType.msoFileDialogOpen);
            if (dlg.Show() != 0)
            {
                if (dlg.SelectedItems.Count > 0)
                {
                    Presentation p = _Application.Presentations.Open(dlg.SelectedItems.Item(1), MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);

                    DocumentWindow w = p.NewWindow();

                    w.Activate();

                    //if (p.Windows.Count > 0)
                    //{
                    //    p.Windows[1].Activate();
                    //}
                }
            }

        }

        private void btnSavePresentation_Click(object sender, RoutedEventArgs e)
        {
            _presentation.Save();
            
        }

        private void btnSaveAsPresentation_Click(object sender, RoutedEventArgs e)
        {
            FileDialog dlg = _Application.get_FileDialog(MsoFileDialogType.msoFileDialogSaveAs);
            if (dlg.Show() != 0)
            {
                _presentation.SaveAs(dlg.Item);     
            }
        }

        #endregion
    }
}